package com.rederxu.tools;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.rederxu.farmer.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class Util {

	/**
	 *返回网络信息
	 * @return 返回是否有网络
	 */
	public static boolean isNetWorkAvailable(Context context) {
		ConnectivityManager connectivitymanager = (ConnectivityManager) context.getSystemService(
				Context.CONNECTIVITY_SERVICE);
		if (connectivitymanager == null) {
			return false;
		}
		NetworkInfo info = connectivitymanager.getActiveNetworkInfo();
		if (info == null || !info.isAvailable()) {
			return false;
		}
		return true;
	}

	public static String getDate(long l) {
		Date date = new Date(l * 1000);
		Date today = new Date(System.currentTimeMillis());
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		if (format.format(date).equals(format.format(today))) {
			return new SimpleDateFormat("HH:mm").format(date);
		} else {
			return new SimpleDateFormat("MM-dd").format(date);
		}
	}

	/**
	 * 列表时间显示
	 * @param timeMillis
	 * @return
	 */
	public static String getPublishedTime(Context context, long timeMillis) {
		long currentTime = System.currentTimeMillis();

		long times = currentTime - timeMillis;

		/**
		 * 一天的时间差 毫秒
		 */
		long dayTime = 24 * 60 * 60 * 1000L;

		/**
		 * 一小时的时间差 毫秒
		 */
		long hourTime = 60 * 60 * 1000L;
		/**
		 * 一分钟的时间差 毫秒
		 */
		long minuteTime = 60 * 1000L;

		if (times >= dayTime) {

			int days = (int) Math.floor((double) times / (double) dayTime);
			if (days == 1) {
				return String.format(context.getString(R.string.x_day_ago), days);
			} else {
				return String.format(context.getString(R.string.x_days_ago), days);
			}
		} else if (times > hourTime) {
			int hours = (int) Math.floor((double) times / (double) hourTime);
			if (hours == 1) {
				return String.format(context.getString(R.string.x_hour_ago), hours);
			} else {
				return String.format(context.getString(R.string.x_hours_ago), hours);
			}
		} else {
			int minutes = (int) Math.floor((double) times / (double) minuteTime);
			if (minutes <= 0) {
				minutes = 1;
			}
			if (minutes == 1) {
				return String.format(context.getString(R.string.x_min_ago), minutes);
			} else {
				return String.format(context.getString(R.string.x_mins_ago), minutes);
			}
		}
	}

	private static final long SIZE_500K = 400 * 1024L;

	public static boolean isJPG(String fileName) {
		if (!TextUtils.isEmpty(fileName)) {
			String extension = FileUtils.getFileExtension(fileName);
			return "jpg".equalsIgnoreCase(extension) || "jpeg".equalsIgnoreCase(extension) || "jpe".equalsIgnoreCase(extension);
		}
		return false;
	}

	public static boolean isPNG(String fileName) {
		if (!TextUtils.isEmpty(fileName)) {
			String extension = FileUtils.getFileExtension(fileName);
			return "png".equalsIgnoreCase(extension);
		}
		return false;
	}

	//============下面方法移植mobo，压缩图片到500k，start==================

	/**
	 * 压缩存储图片到500KB左右，只支持jpg和png格式图片
	 * 
	 * @param srcFile
	 * @param destFile
	 * @return
	 */
	public static boolean compressImageTo500KB(File srcFile, File destFile) {
		boolean isOk = false;
		if (srcFile != null && srcFile.exists() && destFile != null) {
			FileInputStream fis = null;

			try {
				if (SIZE_500K >= srcFile.length() && (isJPG(srcFile.getAbsolutePath()) || isPNG(srcFile.getAbsolutePath()))) {
					Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.PNG; // 默认压缩成png格式图片

					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inJustDecodeBounds = true;

					fis = new FileInputStream(srcFile.getAbsolutePath());
					FileDescriptor fd = fis.getFD();
					BitmapFactory.decodeFileDescriptor(fd, null, options);
					options.inJustDecodeBounds = false;

					int reqHeight = 800;
					int reqWidth = 480;
					options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

					int quality = 0; // 压缩比例，只在jpg格式有效，png格式忽略
					if (isJPG(srcFile.getAbsolutePath())) {
						compressFormat = Bitmap.CompressFormat.JPEG;
						quality = getImageOptions(BitmapFactory.decodeFileDescriptor(fd, null, options)); // jpg格式压缩率，和上面的比例系数搭配使用
					}
					isOk = saveBitmapToFile(rotateBitMap(srcFile.getAbsolutePath(), BitmapFactory.decodeFileDescriptor(fd, null, options)),
							compressFormat, quality, destFile);
					if (!isOk) {
						isOk = copyFile(srcFile, destFile);
					}
				} else {

					Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.PNG; // 默认压缩成png格式图片

					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inJustDecodeBounds = true;

					fis = new FileInputStream(srcFile.getAbsolutePath());
					FileDescriptor fd = fis.getFD();
					BitmapFactory.decodeFileDescriptor(fd, null, options);
					options.inJustDecodeBounds = false;

					int reqHeight = 800;
					int reqWidth = 480;
					options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

					int quality = 0; // 压缩比例，只在jpg格式有效，png格式忽略
					if (isJPG(srcFile.getAbsolutePath())) {
						compressFormat = Bitmap.CompressFormat.JPEG;
						quality = getImageOptions(BitmapFactory.decodeFileDescriptor(fd, null, options)); // jpg格式压缩率，和上面的比例系数搭配使用
					}
					isOk = saveBitmapToFile(rotateBitMap(srcFile.getAbsolutePath(), BitmapFactory.decodeFileDescriptor(fd, null, options)),
							compressFormat, quality, destFile);
					if (!isOk) {
						isOk = copyFile(srcFile, destFile);
					}
				}

			} catch (IOException e) {
				Log.e("compressImageTo500KB",e.toString());
			} catch (OutOfMemoryError e) {
				System.gc();
				Log.e("compressImageTo500KB",e.toString());
			} finally {
				try {
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
					Log.e("compressImageTo500KB",e.toString());
				}
			}
		}
		return isOk;
	}

	/**
	 * 计算按图片大小压缩比
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (width > height && width > reqWidth) {// 如果宽度大的话根据宽度固定大小缩放
			inSampleSize = (width / reqWidth);
		} else if (width < height && height > reqHeight) {// 如果高度高的话根据宽度固定大小缩放
			inSampleSize = (height / reqHeight);
		}
		if (inSampleSize < 1) {
			inSampleSize = 1;
		}

		return inSampleSize;
	}

	/**
	 * 图片按质量压缩
	 * 
	 * @param bitmap
	 * @return
	 */
	private static int getImageOptions(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		int options = 100;
		while (baos.toByteArray().length / 1024 > 499) {
			baos.reset();
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);
			options -= 5;
		}
		return options;
	}

	/**
	 * 用于压缩时旋转图片
	 * 
	 * @param srcFilePath
	 * @param bitmap
	 * @return
	 * @throws IOException
	 * @throws OutOfMemoryError
	 */
	public static Bitmap rotateBitMap(String srcFilePath, Bitmap bitmap) throws IOException, OutOfMemoryError {
		ExifInterface exif = null;
		exif = new ExifInterface(srcFilePath);
		float degree = 0F;
		if (exif != null) {
			switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90F;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180F;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270F;
				break;
			default:
				break;
			}
		}
		Matrix matrix = new Matrix();
		matrix.setRotate(degree, bitmap.getWidth(), bitmap.getHeight());
		Bitmap b2 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		if (bitmap != b2) {
			bitmap.recycle();
			bitmap = b2;
		}
		return bitmap;
	}

	private static final int DEFAULT_BUFFER_SIZE = 8 * 1024;

	/**
	 * 拷贝文件
	 * 
	 * @param sourceFile
	 *            源文件
	 * @param destFile
	 *            目标文件
	 * @return 是否拷贝成功
	 */
	public static boolean copyFile(File sourceFile, File destFile) {
		boolean isCopyOk = false;
		byte[] buffer = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		// 如果此时没有文件夹目录就创建
		String canonicalPath = "";
		try {
			canonicalPath = destFile.getCanonicalPath();
		} catch (IOException e) {
			Log.e("copyFile",e.toString());
		}
		if (!destFile.exists()) {
			if (canonicalPath.lastIndexOf(File.separator) >= 0) {
				canonicalPath = canonicalPath.substring(0, canonicalPath.lastIndexOf(File.separator));
				File dir = new File(canonicalPath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
			}
		}

		try {
			bis = new BufferedInputStream(new FileInputStream(sourceFile), DEFAULT_BUFFER_SIZE);
			bos = new BufferedOutputStream(new FileOutputStream(destFile), DEFAULT_BUFFER_SIZE);
			buffer = new byte[DEFAULT_BUFFER_SIZE];
			int len = 0;
			while ((len = bis.read(buffer, 0, DEFAULT_BUFFER_SIZE)) != -1) {
				bos.write(buffer, 0, len);
			}
			bos.flush();
			isCopyOk = sourceFile != null && sourceFile.length() == destFile.length();
		} catch (IOException e) {
			Log.e("copyFile",e.toString());
		} finally {
			try {
				if (bos != null) {
					bos.close();
					bos = null;
				}
				if (bis != null) {
					bis.close();
					bis = null;
				}
				buffer = null;
			} catch (IOException e) {
				Log.e("copyFile",e.toString());
			}
		}
		return isCopyOk;
	}

	/**
	 * 保存Bitmap到本地文件
	 * 
	 * @param bitmap
	 * @param format
	 * @param quality
	 *            1-100，只对JPG格式有效，PNG格式忽略该参数
	 * @param file
	 */
	public static boolean saveBitmapToFile(Bitmap bitmap, Bitmap.CompressFormat format, int quality, File file) {
		boolean isSave = false;
		if (file != null && bitmap != null && !bitmap.isRecycled()) {
			FileOutputStream fos = null;
			try {
				if (!file.exists()) {
					String canonicalPath = file.getCanonicalPath();
					if (canonicalPath.lastIndexOf(File.separator) >= 0) {
						canonicalPath = canonicalPath.substring(0, canonicalPath.lastIndexOf(File.separator));
						File dir = new File(canonicalPath);
						if (!dir.exists()) {
							dir.mkdirs();
						}
					}
					file.createNewFile();
				}
				if (file.exists()) {
					fos = new FileOutputStream(file);
					isSave = bitmap.compress(format, quality, fos);
					fos.flush();
					// bitmap.recycle();
				}
			} catch (IOException e) {
				Log.e("saveBitmapToFile",e.toString());
			} finally {
				try {
					if (fos != null) {
						fos.close();
					}
				} catch (IOException e) {
					Log.e("saveBitmapToFile",e.toString());
				}
			}
		}
		return isSave;
	}


	/**
	 * 隐藏键盘
	 * @param context
	 */
	public static void hideKeyBoard(Activity context) {
		try {
			InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (Exception e) {
			//
		}
	}

	/**
	 * 显示键盘
	 * @param context
	 * @param et
	 */
	public static void showKeyBoard(Activity context, EditText et) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(et, 0);
	}

	/**
	 * 切换键盘状态
	 * @param context
	 */
	public static void toggleSoftInput(Context context) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
	}
}